﻿@{
    ViewBag.Title = "商品列表";
}

<div class="row">
    <div class="col-xs-12">
        <p>
            <div class="row">
                <div class="col-sm-6">
                    <div class="input-group-btn">                        
                        模糊查询:
                        <input type="text" id="query-filter"/>
                        商品类别:
                        <select id="query-category"></select>
                        品牌:
                        <select id="query-brand"></select>
                        状态:
                        <select id="query-status">
                            <option value="1">正常</option>
                            <option value="4">等待审核</option>
                            <option value="3">已删除</option>
                        </select>
                        <button class="btn btn-sm btn-info" id="btnRefresh">
                            <i class="icon-refresh bigger-110"></i>刷新
                        </button>
                        <button class="btn btn-sm btn-primary" id="btnNew">
                            <i class="icon-plus bigger-110"></i>创建
                        </button>
                    </div>
                </div>
                <div class="col-sm-6 right">
                </div>
            </div>
        </p>
        <div class="table-responsive">
            <table id="businessTable" class="table table-striped table-bordered table-hover">
                <thead>
                    <tr>
                        <th>编号</th>
                        <th>名称</th>
                        <th>类别</th>
                        <th>品牌</th>
                        <th>单位</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>
<!-- 模态框（Modal） -->
<div class="modal fade" id="newModal" tabindex="-1" role="dialog"
     aria-labelledby="newModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:70%;">
        <div class="modal-content">
            <div class="modal-header">
                @*<button type="button" class="close"
                            data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>*@
                <h4 class="modal-title" id="newModalLabel">
                    创建商品
                </h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form" id="formNew">
                    <div class="form-group">
                        <label class="col-sm-2 control-label no-padding-right" for="newName"> 名称 </label>
                        <div class="col-sm-4">
                            <input type="text" id="newName" placeholder="输入名称..." class="col-xs-12 col-sm-12" />
                        </div>
                        <label class="col-sm-2 control-label no-padding-right" for="newCategory"> 分类 </label>
                        <div class="col-sm-4">
                            <select id="newCategory" class="col-xs-12 col-sm-12"></select>
                        </div>
                    </div>
                    <div class="space-4"></div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label no-padding-right" for="newBrand"> 品牌 </label>
                        <div class="col-sm-4">
                            <select id="newBrand" class="col-xs-12 col-sm-12"></select>
                        </div>
                        <label class="col-sm-2 control-label no-padding-right" for="newUnit"> 单位 </label>
                        <div class="col-sm-4">
                            <select id="newUnit" class="col-xs-12 col-sm-12"></select>
                        </div>
                    </div>
                    <div class="space-4"></div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label no-padding-right" for="newModel"> 型号 </label>
                        <div class="col-sm-4">
                            <input type="text" id="newModel" class="col-xs-12 col-sm-12" />
                        </div>
                        <label class="col-sm-2 control-label no-padding-right" for="newTaxRate">税率</label>
                        <div class="col-sm-4">
                            <input type="text" id="newTaxRate" class="col-xs-12 col-sm-12" />
                        </div>
                    </div>
                    <div class="space-4"></div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label no-padding-right" for="newCost"> 成本 </label>
                        <div class="col-sm-4">
                            <input type="text" id="newCost" class="col-xs-12 col-sm-12" />
                        </div>
                        <label class="col-sm-2 control-label no-padding-right" for="newPrice"> 价格 </label>
                        <div class="col-sm-4">
                            <input type="text" id="newPrice" class="col-xs-12 col-sm-12" />
                        </div>
                    </div>
                    <div class="space-4"></div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label no-padding-right" for="newSalesCommissionType"> 销售提成 </label>
                        <div class="col-sm-4">
                            <select id="newSalesCommissionType" class="col-xs-12 col-sm-12">
                                <option value="1">不提成</option>
                                <option value="2">固定金额</option>
                                <option value="3">百分比</option>
                            </select>
                        </div>
                        <label class="col-sm-2 control-label no-padding-right" for="newSalesCommission"> 比例/金额 </label>
                        <div class="col-sm-4">
                            <input type="text" id="newSalesCommission" class="col-xs-12 col-sm-12" />
                        </div>
                    </div>
                    <div class="space-4"></div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label no-padding-right" for="newDescription"> 描述 </label>
                        <div class="col-sm-10">
                            <textarea id="newDescription" class="col-xs-12 col-sm-12"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    关闭
                </button>
                <button type="button" class="btn btn-primary" id="btnSubmitNew">
                    提交更改
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>
@section inlineScript
{
    <script type="text/javascript">
        var oTable = null;
        var g_promise = new Promise();
        var g_categoryArray = null;
        var g_brandArray = null;
        var g_unitArray = null;
        $(document).ready(function () {
            $('#btnRefresh').on('click', function () {
                queryAdvertisementList();
            });
            $('#selectAll').on('change', function () {
                $('input[name=selectItem]').each(function (index, element) {
                    if (element.checked) {
                        $(element).prop('checked', false);
                    } else {
                        $(element).prop('checked', true);
                    }
                });
            });
            $('#btnDelete').on('click', function () {
                var idArray = [];
                $('input[name=selectItem]').each(function (index, element) {
                    if (element.checked) {
                        idArray.push($(element).attr('data-id'));
                    }
                });
                onDeleteMany(idArray);
            });
            $('#btnNew').on('click', function () {
                $('#newModal').modal({});
                if (g_categoryArray != null) {
                    $('#newCategory option').remove();
                    for (var index = 0; index < g_categoryArray.length; index++) {
                        $('#newCategory').append('<option value="' + g_categoryArray[index].code + '">' + g_categoryArray[index].name + '</option>');
                    }
                }
                if (g_brandArray != null) {
                    $('#newBrand option').remove();
                    for (var index = 0; index < g_brandArray.length; index++) {
                        $('#newBrand').append('<option value="' + g_brandArray[index].code + '">' + g_brandArray[index].name + '</option>')
                    }
                }
                queryUnitList();
            });
            $('#btnSubmitNew').on('click', function () {
                if (window.confirm('是否要创建新商品?') == false)
                    return;
                var material = {};
                material.Name = $('#newName').val();
                material.Category = $('#newCategory').val();
                material.TaxRate = $('#newTaxRate').val();
                material.Model = $('#newModel').val();
                material.Cost = $('#newCost').val();
                material.Price = $('#newPrice').val();
                material.Brand = $('#newBrand').val();
                material.Unit = $('#newUnit').val();
                material.SalesCommissionType = $('#newSalesCommissionType').val();
                material.SalesCommission = $('#newSalesCommission').val();
                material.Description = $('#newDescription').val();
                $.ajax({
                    type: "POST",
                    url: "@Url.Content("~/api/asms/Create/Material")",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(material),
                    success: function (data) {
                        if (data.isSuccess) {
                            alert('操作成功!');
                            $('#newModal').modal('hide');
                            queryAdvertisementList();
                        } else {
                            alert(data.message);
                        }
                    },
                    error: function (data) {
                        alert('error');
                    }
                });
            });

            queryCategoryList().then(queryBrandList).then(queryAdvertisementList);
        });

        function queryBrandList() {
            $.ajax({
                url: "@Url.Content("~/api/asms/Query/MasterDataItemPagedList")",
                data: {
                    'MasterDataCode': 'MATERIALBRAND',
                    'start': 0,
                    'limit': 9999
                },//, sortName: propertyNames[sortIndex], sortDirection: sortDirection },
                type: 'get',
                dataType: 'json',
                async: false,
                success: function (result) {
                    if (result.isSuccess) {
                        g_brandArray = result.data.items;
                        $('#query-brand option').remove();
                        $('#query-brand').append('<option value="" selected="selected">全部</option>');
                        for (var index = 0; index < g_brandArray.length; index++) {
                            $('#query-brand').append('<option value="' + g_brandArray[index].code + '">' + g_brandArray[index].name + '</option>')
                        }
                        g_promise.resolve();
                    } else {
                        g_promise.reject();
                    }
                },
                error: function (msg) {
                    g_promise.reject();
                }
            });
            return g_promise;
        }

        function queryUnitList() {
            if (g_unitArray == null) {
                $.ajax({
                    url: "@Url.Content("~/api/asms/Query/MasterDataItemPagedList")",
                    data: {
                        'MasterDataCode': 'MATERIALUNIT',
                        'start': 0,
                        'limit': 9999
                    },//, sortName: propertyNames[sortIndex], sortDirection: sortDirection },
                    type: 'get',
                    dataType: 'json',
                    async: false,
                    success: function (result) {
                        if (result.isSuccess) {
                            g_unitArray = result.data.items;
                            $('#newUnit option').remove();
                            for (var index = 0; index < g_unitArray.length; index++) {
                                $('#newUnit').append('<option value="' + g_unitArray[index].code + '">' + g_unitArray[index].name + '</option>')
                            }
                            g_promise.resolve();
                        } else {
                            g_promise.reject();
                        }
                    },
                    error: function (msg) {
                        g_promise.reject();
                    }
                });
            } else {
                g_promise.resolve();
            }
            return g_promise;
        };

        function queryCategoryList() {
            $.ajax({
                url: "@Url.Content("~/api/asms/Query/MasterDataItemPagedList")",
                data: {
                    'MasterDataCode': 'MATERIALCATEGORY',
                    'start': 0,
                    'limit': 9999
                },//, sortName: propertyNames[sortIndex], sortDirection: sortDirection },
                type: 'get',
                dataType: 'json',
                async: false,
                success: function (result) {
                    if (result.isSuccess) {
                        g_categoryArray = result.data.items;
                        $('#query-category option').remove();
                        $('#query-category').append('<option value="" selected="selected">全部</option>');
                        for (var index = 0; index < result.data.items.length; index++) {
                            $('#query-category').append('<option value="' + result.data.items[index].code + '">' + result.data.items[index].name + '</option>');
                        }
                        g_promise.resolve();
                    } else {
                        g_promise.reject();
                    }
                },
                error: function (msg) {
                    g_promise.reject();
                }
            });
            return g_promise;
        };

        function queryAdvertisementList() {
            if (oTable) {
                oTable.fnClearTable();
            }
            oTable = $("#businessTable").dataTable({
                bRetrieve: true,
                "bLengthChange": false, //改变每页显示数据数量
                "iDisplayLength": 20,
                "bFilter": false, //过滤功能
                "bProcessing": false, // 是否显示取数据时的那个等待提示
                "bServerSide": true,//这个用来指明是通过服务端来取数据
                "sAjaxSource": "@Url.Content("~/API/ASMS/Query/MaterialPagedList")",//这个是请求的地址
                "fnServerData": retrieveData, // 获取数据的处理函数
                "aoColumns": [
                    {
                        "sWidth": '120px',
                        mData: "code",
                        bSortable: false
                    },
                    {
                        mData: "name",
                        bSortable: false
                    },
                    {
                        mData: "categoryName",
                        bSortable: false
                    },
                    {
                        mData: "brandName",
                        bSortable: false
                    },
                    {
                        "sWidth": '90px',
                        mData: "unitName",
                        bSortable: false
                    },
                    {
                        bSortable: false,
                        mData: "status",
                        "sWidth": '120px',
                        mRender: function (data, type, full) {
                            if (data == 1) {
                                return "正常";
                            } else if (data == 2) {
                                return "已禁用";
                            } else if (data == 3) {
                                return "已删除";
                            } else if (data == 4) {
                                return "等待审核";
                            }
                            return 'unknown';
                        }
                    },
                    {
                        //"sTitle": "Operation",
                        mData: null,
                        "sWidth": '140px',
                        bSortable: false,
                        "mRender": function (data, type, full) {
                            return null;
                        }
                    }
                ]
                //,"aoColumnDefs": [{ "bSortable": false, "aTargets": [0, 1, 2, 3] }]
            });
        }

        // 3个参数的名字可以随便命名,但必须是3个参数,少一个都不行
        function retrieveData(sSource, aoData, fnCallback) {
            var start = 0;
            var limit = 0;
            var propertyNames = new Array();
            var sortIndex = 0;
            var sortDirection;
            for (var index = 0; index < aoData.length; index++) {
                if (aoData[index].name == 'iDisplayStart') {
                    start = aoData[index].value;
                } else if (aoData[index].name == 'iDisplayLength') {
                    limit = aoData[index].value;
                } else if (aoData[index].name.indexOf('mDataProp_') == 0) {
                    propertyNames.push(aoData[index].value);
                } else if (aoData[index].name.indexOf('iSortCol_') == 0) {
                    sortIndex = aoData[index].value;
                } else if (aoData[index].name.indexOf('sSortDir_') == 0) {
                    sortDirection = aoData[index].value;
                }
            }
            $.ajax({
                url: sSource,//这个就是请求地址对应sAjaxSource
                data: {
                    'filter': $('#query-filter').val(),
                    'category': $('#query-category').val(),
                    'brand': $('#query-brand').val(),
                    'status': $('#query-status').val(),
                    'start': start,
                    'limit': limit
                },//, sortName: propertyNames[sortIndex], sortDirection: sortDirection },
                type: 'get',
                dataType: 'json',
                async: false,
                success: function (result) {
                    if (result.isSuccess) {
                        fnCallback({
                            sEcho: aoData[0].value,
                            iTotalRecords: result.data.total,
                            iTotalDisplayRecords: result.data.total,
                            aaData: result.data.items
                        });
                    }
                },
                error: function (msg) {
                }
            });
        }

        function onDelete(el) {
            var id = $(el).attr('data-id');  // save
            if (!id) {
                return;
            }
            if (window.confirm("是否要删除广告?")) {
                $.ajax({
                    type: "POST",
                    url: "@Url.Content("~/api/apms/advertisement/delete")",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({ 'id': id }),
                    success: function (data) {
                        if (data.isSuccess) {
                            queryAdvertisementList();
                        } else {
                            alert(data.message);
                        }
                    },
                    error: function (data) {
                        alert('error');
                    }
                });
            }
        };
        function onDeleteMany(idArray) {
            if (idArray == null || idArray.length == 0)
                return;
            if (window.confirm("是否要删除选中的广告?")) {
                $.ajax({
                    type: "POST",
                    url: "@Url.Content("~/api/apms/advertisement/deleteMany")",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({ 'idArray': idArray }),
                    success: function (data) {
                        if (data.isSuccess) {
                            queryAdvertisementList();
                        } else {
                            alert(data.message);
                        }
                    },
                    error: function (data) {
                        alert('error');
                    }
                });
            }
        }
    </script>
}
